package com.wqtz.chechai.utils;

import com.orhanobut.logger.Logger;
import com.wqtz.chechai.api.Constans;

import cn.hugeterry.updatefun.config.UpdateKey;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 项目名称： CheChai
 * 创建人 :  Kisum
 * 创建时间: 2017/1/17
 * OkHttpUtils的post请求
 */

// Constants.APP_KEY 和 Constants.APP_ID 在 LeanCloud 控制台获取
// String MD5Util.string2MD5(String s); 进行 MD5 加密的一个方法。

public class OkHttpUtils {

    private static OkHttpUtils OkHttpUtils = new OkHttpUtils();
    private static OkHttpClient client;

    public static OkHttpUtils getInstance() {
        client = new OkHttpClient().newBuilder().build();
        return OkHttpUtils;
    }
    public static Boolean postJson(String target, String json) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, json);
        long timestamp = System.currentTimeMillis();
        String sign = MD5Util.string2MD5(timestamp + Constans.LEANCLOUD_APP_KEY);
        Request request = new Request.Builder()
                .addHeader("X-LC-Id", Constans.LEANCLOUD_APP_ID)
                .addHeader("X-LC-Sign", sign + "," + timestamp)
                .url(target)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            //判断请求是否成功
            if (response.isSuccessful()) {
                LogUtils.e("请求成功。。。。。");
                return true;
            } else {
                LogUtils.e("请求失败。。。。。");
                Logger.e(response.body().string());
            }
        } catch (Exception e) {
            Logger.e(e.toString());
        }
        return false;
    }
}
